import { nextTick, onBeforeMount } from 'vue'
import { useUa } from './ua'

type ThemeType = 'light' | 'dark'

const attributeName = 'theme'

function setTheme(theme: ThemeType) {
  const ua = useUa()

  if (ua.isClient.value) {
    API.request
      .http<string>({
        url: 'https://t11.baidu.com/it/u=678728035,1458649380&fm=173&app=49&f=JPEG',
        responseType: 'arraybuffer'
      })
      .then(response => {
        console.log(response)
      })
  }

  nextTick(() => {
    document.documentElement.dataset[attributeName] = theme
    localStorage.setItem(attributeName, theme)
  })
}

export function useTheme() {
  onBeforeMount(() => {
    const localTheme = localStorage.getItem(attributeName) as ThemeType
    if (localTheme) setTheme(localTheme)
  })

  return {
    light() {
      const theme: ThemeType = 'light'
      setTheme(theme)
    },
    dark() {
      const theme: ThemeType = 'dark'
      setTheme(theme)
    },
    toggle() {
      const theme: ThemeType = (document.documentElement.dataset[attributeName] || 'light') as ThemeType
      setTheme(theme === 'dark' ? 'light' : 'dark')
    }
  }
}
